package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"news-feed/cache"
	"news-feed/models"
	"strconv"
	"time"
)

func Create(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.New{
		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "发布成功",
		})
		return
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var news []models.New
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&news)
		jsonData, _ := json.Marshal(&news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &news)
	}
	var total int64
	models.DB.Model(&models.New{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  news,
		"msg":   "success",
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var new1 models.New
	redis_key := "list_page_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&new1)
		jsonData, _ := json.Marshal(&new1)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &new1)
	}
	var total int64
	models.DB.Model(&models.New{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  new1,
		"msg":   "success",
		"total": total,
	})
	return
}
